<template>
  <DFModal
    ref="basicModalRef"
    class="basicModal"
    :title="$t('login.form.modalTitle')"
    :width="800"
    @register="modalRegister"
    @on-ok="okModalFn"
  >
    <template #default>
      <div class="flex">
        <n-popconfirm @positive-click="handlePositiveClickFn">
          <template #trigger>
            <n-button type="warning">
              {{ $t('login.form.parameterReset') }}
            </n-button>
          </template>
          {{ $t('login.tips.isParameterReset') }}
        </n-popconfirm>
      </div>

      <DFForm class="basicForm" @register="modalFormRegister" />
    </template>
  </DFModal>
</template>

<script lang="ts" setup name="OptionsModal">
import { NPopconfirm } from 'naive-ui';

import { DFModal, useModal } from '@/components/DFModal';

import { DFForm, FormSchema, useForm } from '@/components/DFForm/index';

import { t } from '@/i18n';

import { storage } from '@/utils/Storage';

const [
  modalRegister,
  { openModal, closeModal, setSubLoading: setSubLoadingFn }
] = useModal({});

const modalFormSchemas: FormSchema[] = [
  {
    field: 'host',
    label: 'host',
    component: 'NInput',
    defaultValue: storage.get('host')||'localhost',
    componentProps: {
      maxlength: 250,
      clearable: true,
      placeholder: t('common.form.plInput')
    },
    rules: [
      {
        required: true,
        trigger: ['blur'],
        message: t('common.formTipMsg.input')
      }
    ]
  },
];

const [
  modalFormRegister,
  {
    validate: modalFormValidateFn,
    getFieldsValue: getModalFormValFn
  }
] = useForm({
  gridProps: { cols: 1 },
  collapsedRows: 3,
  labelWidth: 180,
  layout: 'horizontal',
  showActionButtonGroup: false,
  schemas: modalFormSchemas
});

const setConfigFn = async (data?) => {
  if (window.electron) {
    window.electron.setConfig(data);
  }
}

const okModalFn = async () => {
  try {
    const isSubmit = await modalFormValidateFn();

    if (!isSubmit) {
      const data = getModalFormValFn();

      // for (const i in data) {
      //   if (data[i]) {
      //     switch (i) {
      //       default:
      //         storage.set(i, data[i]);
      //         break;
      //     }
      //   }
      // }
      // modalSubmitFn();

      await setConfigFn(data)

      closeModal();

      nextTick(() => {
        setSubLoadingFn(false);

        location.reload();
      });
    } else {
      setSubLoadingFn(false);
    }
  } catch (e) {
    console.log(e);

    setSubLoadingFn(false);
  }
};

const openModalFn = async () => {
  openModal();
};

const handlePositiveClickFn = async() => {
  const data = getModalFormValFn();

  for (const i in data) {
    storage.remove(i);
  }

  await setConfigFn()

  nextTick(() => {
    location.reload();
  });
};

// nextTick(() => {
//   openModalFn();
// });

defineExpose({ openModalFn });
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  margin-bottom: 24px;
  .get-ip {
    margin-left: 12px;
  }
}
</style>
